Explain the principle of mutual exclusion and give an illustration to show that ensuring mutual exclusion is important. [6]
The principle of mutual exclusion is preventing two threads from being in the critical section at the same time, where the critical section is exclusive access to some shared resource such as a memory location.
For example, if we have two threads that were to read a counter variable, increase it’s value by 1 and then write back the value to memory. The critical section of this would be when the thread obtains the value of the counter variable. The ideal execution would be that:
c has value 0
thread 1 reads the value of counter c, namely 0
thread 1 increments its value, to 1
thread 1 writes its value back to c
so now c has value 1
thread 2 reads the value of counter c, namely 1
thread 2 increments its value, to 2
thread 2 writes its value back to c
so now c has value 2
However, what could happen is:
c has value 0
thread 1 reads the value of counter c, namely 0
thread 1 increments its value, to 1
thread 2 reads the value of counter c, namely 0
thread 1 writes its value back to c
so now c has value 1
thread 2 increments its value, to 1
thread 2 writes its value back to c
so now c has value 1
Clearly, the second execution has failed to achieve what was intended due to the lack of mutual exclusion. Hence mutual exclusion is important
(Rathin)